package com.atguigu.flinkSql2;


import com.atguigu.been.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;

import java.util.Random;

import static org.apache.flink.table.api.Expressions.$;
import static org.apache.flink.table.api.Expressions.call;


/**
 * @author wky
 * @create 2021-07-22-10:40
 */

// 标量函数 udf 一进一出
public class Flink06_UDF_ScalarFunction {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        StreamTableEnvironment tableEnvironment = StreamTableEnvironment.create(env);
        //将默认时区从格林威治时区改为东八区
        Configuration configuration = tableEnvironment.getConfig().getConfiguration();
        configuration.setString("table.local-time-zone", "GMT");
        //2.读取文件得到DataStream
        DataStreamSource<WaterSensor> waterSensorDataStreamSource = env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                new WaterSensor("sensor_1", 2000L, 20),
                new WaterSensor("sensor_2", 3000L, 30),
                new WaterSensor("sensor_1", 4000L, 40),
                new WaterSensor("sensor_1", 5000L, 50),
                new WaterSensor("sensor_2", 6000L, 60));

        //3.将流转换为动态表
        Table table = tableEnvironment.fromDataStream(waterSensorDataStreamSource);


//        //不注册函数直接使用 只能在tableApi中使用
//        table.select($("id"),call(MyUdf.class,$("id"))).execute().print();
//        注册函数 再使用 可以在sql语句中
        tableEnvironment.createTemporarySystemFunction("udf",MyUdf.class);
        table.select($("id"),call("udf",$("id"))).execute().print();
        tableEnvironment.executeSql("select id," +
                "vc," +
                "udf(id) " +
                "from " +table).print();


    }
    public static class MyUdf  extends ScalarFunction{
        public String eval(String value){
            Random random = new Random();
            return value+random.nextInt(10);
        }

    }
}
